package com.hankol.community.adapter

import android.app.Activity
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.baselibrary.bean.*
import com.baselibrary.manager.DialogManager
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.net.APIResponse
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.SmallVipHeardImgView
import com.baselibrary.view.banner.Banner
import com.baselibrary.view.banner.BannerConfig
import com.baselibrary.view.banner.Transformer
import com.baselibrary.view.banner.loader.GlideImageLoader
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.hankol.community.R
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.viewmodel.CommunityViewModel
import com.like.LikeButton
import com.like.OnLikeListener
import java.util.*


/**
 *@author:hanke
 *2022/3/31
 *desc:
 */
class DiscoverChannelAdapter(val activity: Activity,data: List<StreamData.DataDTO.Data>, val viewModel: CommunityViewModel, val communityHelp: CommunityHelp) : BaseMultiItemQuickAdapter<StreamData.DataDTO.Data, BaseViewHolder>(data) {
    private var mCallback: Callback? = null
    private var type = 0
    fun setType(type: Int) {
        this.type = type
    }

    init {
        addItemType(StreamData.busiType_top_article, R.layout.item_ad_banner) //置顶广告

        addItemType(StreamData.busiType_timeline_image, R.layout.item_common_dynamic) //图片动态 timeline 21

        addItemType(StreamData.busiType_timeline_video, R.layout.item_common_dynamic) //视频动态 timeline 22

        addItemType(StreamData.busiType_live, R.layout.item_live_dynamic) //直播 timeline 3

        addItemType(StreamData.busiType_article, R.layout.item_common_dynamic) //专栏文章 article 5

        addItemType(StreamData.busiType_qa_question, R.layout.item_common_dynamic) //问答 qa_question 7

        addItemType(StreamData.busiType_advertisement, R.layout.item_common_dynamic) //广告 advertisement 10

        addItemType(StreamData.busiType_wk_entries, R.layout.item_common_dynamic) //词条 wk_entries 8

        addItemType(StreamData.busiType_forum, R.layout.item_common_dynamic) //视频（讲堂）forum 6

        addItemType(StreamData.busiType_channel, R.layout.item_common_dynamic) //专栏 channel 4

        addItemType(StreamData.busiType_party, R.layout.item_common_dynamic) //约局 party


    }

    override fun convert(helper: BaseViewHolder, item: StreamData.DataDTO.Data) {
        when (item.busiType) {
            StreamData.busiType_top_article -> showAdBanner(helper, item)
            StreamData.busiType_timeline_image -> (showDynamic(helper, item, false))
            StreamData.busiType_timeline_video -> (showDynamic(helper, item, true))
            StreamData.busiType_live -> (showLive(helper, item))
        }
    }

    private fun showAdBanner(helper: BaseViewHolder, item: StreamData.DataDTO.Data) {
        val tlObj = item.data
        val tlStr = GsonUtils.toJson(tlObj)
        val datas: List<BannerConfigBean> = GsonUtils.fromJsonArray(tlStr, BannerConfigBean::class.java)
        val urlList: MutableList<String> = ArrayList()
        for (data in datas) {
            urlList.add(data.img)
        }
        val banner = helper.getView<Banner>(R.id.bn_ad);
        banner?.let {
            it.setImageLoader(GlideImageLoader(4))
            it.setDelayTime(5000)
            it.setBannerStyle(BannerConfig.CUSTOM_INDICATOR)
            it.setBannerAnimation(Transformer.Default)
            it.setIndicatorGravity(BannerConfig.CENTER)
            it.setImages(urlList)
            it.setIndicatorGravity(BannerConfig.CENTER)
            it.setOnBannerListener { position -> jumpToAdDetail(datas[position]) }
            it.start()
        }
        val layoutParams: ViewGroup.LayoutParams = banner.layoutParams
        val width = (ScreenUtils.getScreenWidth(mContext) / 2f - ScreenUtils.dpToPx(10)).toInt()
        layoutParams.height = width * 33 / 19
        banner.layoutParams = layoutParams
    }

    private fun jumpToAdDetail(data: BannerConfigBean) {
        if (!DoubleClickHelper.isOnDoubleClick()) {
            ARouterUtils.bannerJump(activity, data.routeType, data.routeUrl, data.appletId)
            SensorsDataManager.instance.homeZhidingClick(data.name)
//            SensorsDataManager.instance.clickAd(data.top == 1.0, data.title, data.channelName)
        }
    }

    private fun showDynamic(helper: BaseViewHolder, item: StreamData.DataDTO.Data, isVideo: Boolean) {
        val tlObj = item.data
        val tlStr = GsonUtils.toJson(tlObj)
        val timeline: ClientStreamTimeline = GsonUtils.parseJsonToBean(tlStr, ClientStreamTimeline::class.java)
        ImageUtils.setImageViewSize(helper.getView(R.id.iv_dynamic_cover), false)
        GlideUtils.loadImg_228(mContext, timeline.cover, helper.getView(R.id.iv_dynamic_cover))
        helper.setText(R.id.tv_dynamic_title, timeline.desc)
        val vipHeardImgView = helper.getView<SmallVipHeardImgView>(R.id.iv_dynamic_head)
        vipHeardImgView.setData(timeline.authorIcon, timeline.isFans === 1, View.INVISIBLE)
        helper.setText(R.id.tv_dynamic_username, timeline.author)
        helper.setText(R.id.tv_dynamic_like_number, NumberUtils.formatBigNum(timeline.supportNum.toString()))
        val likeStatus: LikeButton = helper.getView(R.id.iv_dynamic_like)
        likeStatus.isLiked = timeline.isSupported
        likeStatus.setOnLikeListener(object : OnLikeListener {
            override fun liked(likeButton: LikeButton?) {
                timeline.supportNum = if (timeline.isSupported) timeline.supportNum.minus(1) else timeline.supportNum.plus(1)
                timeline.isSupported = !timeline.isSupported
                helper.setText(R.id.tv_dynamic_like_number, NumberUtils.formatBigNum(timeline.supportNum.toString()))
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    mCallback?.onClickLike(mData.indexOf(item) + headerLayoutCount, item)
                }
            }

            override fun unLiked(likeButton: LikeButton?) {
                timeline.supportNum = if (timeline.isSupported) timeline.supportNum.minus(1) else timeline.supportNum.plus(1)
                timeline.isSupported = !timeline.isSupported
                helper.setText(R.id.tv_dynamic_like_number, NumberUtils.formatBigNum(timeline.supportNum.toString()))
                if (!DoubleClickHelper.isOnDoubleClick()) {
                    mCallback?.onClickLike(mData.indexOf(item) + headerLayoutCount, item)
                }
            }
        })
        helper.setVisible(R.id.iv_play, isVideo)
        helper.setGone(R.id.tv_dynamic_title, !TextUtils.isEmpty(timeline.desc))
        helper.itemView.setOnClickListener {
            if (!DoubleClickHelper.isOnDoubleClick()) {
                if (type == -1) {
                    SensorsDataManager.instance.clickRecommend(timeline.tagCategoryName, timeline.desc, getStateType(timeline.recommendType), if (isVideo) "视频动态" else "图片动态", timeline.tagName)
                }
                if (isVideo) {
                    val hashMap = HashMap<String, Any>()
                    hashMap["id"] = timeline.id
                    hashMap["isOpenComment"] = false
                    hashMap["JumpType"] = 0
                    hashMap["source"] = timeline.tagCategoryName
                    hashMap["bid"] = timeline.id.toString()
                    ARouterUtils.jump(ActivityRouter.ACTIVITY.READ_VIDEO_DETAIL, hashMap, helper.getView(R.id.iv_dynamic_cover))
                } else {
                    val hashMap = HashMap<String, Any>()
                    hashMap["id"] = timeline.id.toString()
                    hashMap["source"] = timeline.tagCategoryName
                    ARouterUtils.jump(ActivityRouter.ACTIVITY.IMAGE_DETAIL, hashMap, helper.getView(R.id.iv_dynamic_cover))
                }
            }
        }

    }

    private fun getStateType(type: Int?): String {
        return when (type) {
            0 -> "普通动态"
            1 -> "推荐动态"
            2 -> "置顶动态"
            else -> "固定位置动态"
        }
    }

    private fun showLive(helper: BaseViewHolder, item: StreamData.DataDTO.Data) {
        val tlObj = item.data
        val tlStr = GsonUtils.toJson(tlObj)
        val liveInfo: ClientStreamLiveRoom = GsonUtils.parseJsonToBean(tlStr, ClientStreamLiveRoom::class.java)
        val liveHead = helper.getView<SmallVipHeardImgView>(R.id.iv_dynamic_head)
        ImageUtils.setImageViewSize(helper.getView(R.id.iv_dynamic_cover), false)
        liveHead.setData(liveInfo.liveIcon, false, View.INVISIBLE)
        GlideUtils.loadImg_228(mContext, liveInfo.cover, helper.getView(R.id.iv_dynamic_cover))
        helper.setText(R.id.tv_dynamic_title, liveInfo.name)
        val tvLiveStatus: TextView = helper.getView(R.id.tv_live_status)
        val ivLiveStatus: ImageView = helper.getView(R.id.iv_live_status)

        if (liveInfo.activity == 1) {//未开始的直播
            helper.setVisible(R.id.tv_dynamic_watch_number, false)
            helper.setVisible(R.id.tv_subscribe, true)
            tvLiveStatus.text = TimeUtil.getLiveTime(liveInfo.startTime)
            GlideUtils.loadImg(mContext, R.drawable.icon_time, ivLiveStatus)
        } else {
            helper.setVisible(R.id.tv_dynamic_watch_number, true)
            helper.setText(R.id.tv_dynamic_watch_number, liveInfo.lookNum.toString())
            helper.setVisible(R.id.tv_subscribe, false)
            tvLiveStatus.text = "直播中"
            GlideUtils.loadGif(mContext, R.drawable.icon_on_live, ivLiveStatus)
        }
        helper.setText(R.id.tv_dynamic_username, SpanUtils.appendEllipsis(liveInfo.liveName, 6))

        val subscribeStatus: TextView = helper.getView(R.id.tv_subscribe)
        subscribeStatus.isSelected = liveInfo.isSubscribe == 1
        helper.setText(R.id.tv_subscribe, if (liveInfo.isSubscribe == 1) "已预约" else "预约")
        subscribeStatus.setOnClickListener {
            if (SpUtils.getInstance().loadUserBean == null || TextUtils.isEmpty(SpUtils.getInstance().loadUserBean.data.token) || SpUtils.getInstance().loadUserBean.data.userRank == 99) { //游客模式{
                AppManager.getAppManager().openLoginPage()
            } else {
                val action: Boolean = liveInfo.isSubscribe == 1
                SensorsDataManager.instance.subscribeLive(action, liveInfo.liveName)
                viewModel.requestSubscribeLive(mContext, action, liveInfo.id.toString(), object : APIResponse<String>(this) {
                    override fun onSuccess(result: String?, json: String?) {
                        liveInfo.isSubscribe = if (action) 0 else 1
                        subscribeStatus.isSelected = liveInfo.isSubscribe == 1
                        helper.setText(R.id.tv_subscribe, if (liveInfo.isSubscribe == 1) "已预约" else "预约")
                    }

                    override fun onFailed(message: String?) {
                        ToastUtils.showShort(mContext, message)
                    }
                })
            }
        }
        helper.itemView.setOnClickListener {
            if (!DoubleClickHelper.isOnDoubleClick()) {
                if (liveInfo.activity == 2) {
                    if (liveInfo.roomCode != "") {
                        if (SpUtils.getInstance().loadUserBean == null || SpUtils.getInstance().loadUserBean.data.userRank == 99) { //游客模式
                            AppManager.getAppManager().openLoginPage()
                        }
                        DialogManager.showRoomCodeDialog(mContext as Activity, object : OnClickListener {
                            override fun onClick(view: View, `object`: Any) {
                                if (`object` is String) {
                                    val content = `object`
                                    if (!CommonUtil.isBlank(liveInfo.roomCode) && !CommonUtil.isBlank(content) && liveInfo.roomCode == content) {
                                        communityHelp.goLiveDetail(mContext as Activity, liveInfo.id)
                                    } else {
                                        ToastUtils.showShort(mContext, "邀请码不正确")
                                    }
                                }
                            }

                            override fun onLongClick(view: View, `object`: Any) {}
                        }, null)
                    } else {
                        if (SpUtils.getInstance().loadUserBean == null || SpUtils.getInstance().loadUserBean.data.userRank == 99) { //游客模式
                            AppManager.getAppManager().openLoginPage()
                        } else {
                            communityHelp.goLiveDetail(mContext as Activity, liveInfo.id)
                        }
                    }
                } else {
                    communityHelp.goLiveInfo(mContext as Activity, liveInfo.id)
                }
            }
        }

    }


    fun setCallback(mCallback: Callback?) {
        this.mCallback = mCallback
    }

    interface Callback {
        fun onClickLike(position: Int, item: StreamData.DataDTO.Data)
    }

}